<?php

require '../src/facebook.php';

// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
  'appId'  => '197834485574',
  'secret' => '2f53f8da25ccdd61536dccfc272c08f9',
  'cookie' => true,
));

// We may or may not have this data based on a $_GET or $_COOKIE based session.
//
// If we get a session here, it means we found a correctly signed session using
// the Application Secret only Facebook and the Application know. We dont know
// if it is still valid until we make an API call using the session. A session
// can become invalid if it has already expired (should not be getting the
// session back in this case) or if the user logged out of Facebook.
$session = $facebook->getSession();
$me = null;
$access_token = null;
// Session based API call.
if ($session) {
  try {
    $uid = $facebook->getUser();
    $me = $facebook->api('/me');
    $access_token = $facebook->getAccessToken();
  } catch (FacebookApiException $e) {
    error_log($e);
  }
}

// login or logout url will be needed depending on current user state.
if ($me) {
  $logoutUrl = $facebook->getLogoutUrl();
} else {
  $loginUrl = $facebook->getLoginUrl();
}

?>
<!doctype html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
  <head>
    <link rel="stylesheet" href="../css/skeleton.css" type="text/css" />
    <link rel="stylesheet" href="../css/jquery-ui-1.7.3.custom.css" type="text/css" />
    <link rel="stylesheet" href="../css/ui.button.css" type="text/css" />
    <link rel="stylesheet" href="./base.css" type="text/css" />
    <link rel="stylesheet" href="./ForceDirected.css" type="text/css" />
    <!--<link rel="stylesheet" href="./Spacetree.css" type="text/css" />-->
    
    <!-- JIT Library File -->
    <script language="javascript" type="text/javascript" src="./jit.js"></script>
    <!-- Example File 
    <script language="javascript" type="text/javascript" src="example1.js"></script>
    -->

    <title></title>
    <style>
      body {
        font-family: 'Lucida Grande', Verdana, Arial, sans-serif;
      }
      h1 a {
        text-decoration: none;
        color: #3b5998;
      }
      h1 a:hover {
        text-decoration: underline;
      }
    </style>
  </head>
  <!--<body onload="init();">-->
  <body>
    <!--
      We use the JS SDK to provide a richer user experience. For more info,
      look here: http://github.com/facebook/connect-js
    -->
    <div id="fb-root"></div>
    <script>
      window.fbAsyncInit = function() {
        FB.init({
          appId   : '<?php echo $facebook->getAppId(); ?>',
          session : <?php echo json_encode($session); ?>, // don't refetch the session when PHP already has it
          status  : true, // check login status
          cookie  : true, // enable cookies to allow the server to access the session
          xfbml   : true // parse XFBML
        });

        // whenever the user logs in, we refresh the page
        FB.Event.subscribe('auth.login', function() {
          window.location.reload();
        });
      };

      (function() {
        var e = document.createElement('script');
        e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
        e.async = true;
        document.getElementById('fb-root').appendChild(e);
      }());
    </script>
    <div >
      <div class="content centered">
        <?php
          if($me){
            echo '<div class="post">';
              echo '<p>'.$me['name'].'</p>';
              echo '<img class="map_img" src="https://graph.facebook.com/'.$uid.'/picture">';              
              echo '<button class="ui-state-active ui-button ui-state-default ui-button-text-only ui-corner-all ui-state-hover"  onclick="init();"><span class="ui-button-text">Ver</span></button>';
            echo '</div>';
            echo '<div class="post">';
              echo '<a href="'.$logoutUrl.'" <img src="http://static.ak.fbcdn.net/rsrc.php/z2Y31/hash/cxrz4k7j.gif">Desconectate: </a>';
            echo '</div>';
          }else{
            echo '<div>Conectate: <fb:login-button></fb:login-button></div>';
          }
        ?>

        <div id="log"></div>
      </div>

      <div class="content centered">
        <!-- Show the CANVAS-->
        <div id="center-container" class="center-container">
            <div id="infovis"></div>
        </div>

        <?php
        if($me){            
            echo '<div class="center-container" id="more_friends">';
            echo '<p>Todos tus Amigos</p>';
            $friends = $facebook->api('/me/friends');
            foreach ($friends['data'] as $k => $person){
              $profile =  $facebook->api('/'.$person['id'].'?access_token='.$access_token);
              echo '<a href="'.$profile['link'].'?sk=photos" target="_new">';
                echo '<img class="map_img avatar option" title="'.$person['name'].'" src="https://graph.facebook.com/'.$person['id'].'/picture">';
              echo '</a>';
            }
            echo '</div>';
        }
        ?>

      </div>
  </div>

    <?php
        if($me){
            $my_info = array();
            $json_friends = array();
            $friends_data = array();
            $introspection_limit = 5;

            // This call will always work since we are fetching public data.
            $friends = $facebook->api('/me/friends?limit='.$introspection_limit);    //we do some INTROSPECTION  ?limit=10
            //$friends = $facebook->api('/me/friends');    //we do some INTROSPECTION  ?limit=10
            foreach ($friends['data'] as $k => $person){
                //add the links first
                $my_info['adjacencies'][] = array(
                    "nodeTo" => $person['id'],
                    "nodeFrom" => $me['id'],
                    "data" => array (
                       '$color' => "#557EAA"
                    )
                  );

                 /*
                //we should find all it's friends
                $dof = $facebook->api('/'.$person['id'].'/photos?access_token='.$access_token);
                //var_dump($dof);

                $data = array();
                foreach ($dof['data'] as $kk => $person_dof){
                    $person_data['adjacencies'][] = array(
                              "nodeTo" => $person_dof['id'],
                              "nodeFrom" => $person['id'],
                              "data" => array (
                                 '$color' => "#557EAA"
                              )
                      );

                    $data['data'] = array(
                                      '$color' => "#EBB056",
                                      '$type' => "star",
                                      '$dim' => 8
                                    );
                    $data['id'] = $person_dof['id'];
                    $data['name'] = $person_dof['link'];
                    $data['img'] = $person_dof['picture'];
                    $friends_data[] = $data;
                }
                */
                
                //add this value data
                $person_data['data'] = array(
                                  '$color' => "#EBB056",
                                  '$type' => "star",
                                  '$dim' => 8
                                );
                $person_data['id'] = $person['id'];
                $person_data['name'] = $person['name'];
                $person_data['img'] = "https://graph.facebook.com/".$person['id']."/picture";

                $friends_data[] = $person_data;

                //$json_friends['adjacencies'][] = $person_data;
                //$json_friends[] = $value;
                //$json_friends[0]['children'][] = $value;
                //jit SpaceTree
                //$json_friends['children'] = array();
                //$json_friends['children'][] = $value;

                /*
                $photos = $facebook->api("/".$person['id']."/photos");
                //var_dump($photos);
                foreach ($photos['data'] as $k => $pic){
                    //var_dump($pic['picture']);
                    echo '<div class=".wrapper_img"><p>'.$pic['name'].'</p>';
                    echo '<img title="'.$pic['name'].'" src="'.$pic['picture'].'"></div>';
                }
                 * 
                 */
            }


            //echo '<pre>'; var_dump($friends_data); echo '</pre>';

            $my_info['id'] = $me['id'];
            $my_info['name'] = $me['name'];
            $my_info['img'] = "https://graph.facebook.com/".$me['id']."/picture";
            $my_info['data'] = array(
                                '$color' => "#EBB056",
                                '$type' => "star",
                                '$dim' => 8);
            //add my friends data
            $json_friends[] = $my_info;
            foreach ($friends_data as $f){
              $json_friends[] = $f;
            }

            //echo '<pre>'; print_r($json_friends); echo '</pre>';
            $data = json_encode($json_friends);
            //echo '<pre>'; print_r($data); echo '</pre>';
        }
    ?>
    <script>
    var labelType, useGradients, nativeTextSupport, animate;

    (function() {
      var ua = navigator.userAgent,
          iStuff = ua.match(/iPhone/i) || ua.match(/iPad/i),
          typeOfCanvas = typeof HTMLCanvasElement,
          nativeCanvasSupport = (typeOfCanvas == 'object' || typeOfCanvas == 'function'),
          textSupport = nativeCanvasSupport
            && (typeof document.createElement('canvas').getContext('2d').fillText == 'function');
      //I'm setting this based on the fact that ExCanvas provides text support for IE
      //and that as of today iPhone/iPad current text support is lame
      labelType = (!nativeCanvasSupport || (textSupport && !iStuff))? 'Native' : 'HTML';
      nativeTextSupport = labelType == 'Native';
      useGradients = nativeCanvasSupport;
      animate = !(iStuff || !nativeCanvasSupport);
    })();

    var Log = {
      elem: false,
      write: function(text){
        if (!this.elem)
          this.elem = document.getElementById('log');
        this.elem.innerHTML = text;
        this.elem.style.left = (500 - this.elem.offsetWidth / 2) + 'px';
      }
    };

    function init(){
        var json = <?php echo $data; ?>;   //fuuuuuck

      // init ForceDirected
      var fd = new $jit.ForceDirected({
        //id of the visualization container
        injectInto: 'infovis',
        //Enable zooming and panning
        //by scrolling and DnD
        Navigation: {
          enable: true,
          //Enable panning events only if we're dragging the empty
          //canvas (and not a node).
          panning: 'avoid nodes',
          zooming: 10 //zoom speed. higher is more sensible
        },
        // Change node and edge styles such as
        // color and width.
        // These properties are also set per node
        // with dollar prefixed data-properties in the
        // JSON structure.
        Node: {
          overridable: true
        },
        Edge: {
          overridable: true,
          color: '#23A4FF',
          lineWidth: 1.2
        },
        //Native canvas text styling
        Label: {
          type: labelType, //Native or HTML
          size: 10,
          style: 'bold'
        },
        //Add Tips
        Tips: {
          enable: true,
          onShow: function(tip, node) {
            //count connections
            var count = 0;
            node.eachAdjacency(function() { count++; });
            //display node info in tooltip
            tip.innerHTML = "<img src="+ node.img +">" + "<div class=\"tip-title\">" + node.name + "</div>"
              + "<div class=\"tip-text\"><b>connections:</b> " + count + "</div>";
          }
        },
        // Add node events
        Events: {
          enable: true,
          //Change cursor style when hovering a node
          onMouseEnter: function() {
            fd.canvas.getElement().style.cursor = 'move';
          },
          onMouseLeave: function() {
            fd.canvas.getElement().style.cursor = '';
          },
          //Update node positions when dragged
          onDragMove: function(node, eventInfo, e) {
              var pos = eventInfo.getPos();
              node.pos.setc(pos.x, pos.y);
              fd.plot();
          },
          //Implement the same handler for touchscreens
          onTouchMove: function(node, eventInfo, e) {
            $jit.util.event.stop(e); //stop default touchmove event
            this.onDragMove(node, eventInfo, e);
          },
          //Add also a click handler to nodes
          onClick: function(node) {
            if(!node) return;
            // Build the right column relations list.
            // This is done by traversing the clicked node connections.
            var html = "<h4>" + node.name + "</h4><b> connections:</b><ul><li>",
                list = [];
            node.eachAdjacency(function(adj){
              list.push(adj.nodeTo.name);
            });
            //append connections information
            $jit.id('inner-details').innerHTML = html + list.join("</li><li>") + "</li></ul>";
          }
        },
        //Number of iterations for the FD algorithm
        iterations: 200,
        //Edge length
        levelDistance: 130,
        // Add text to the labels. This method is only triggered
        // on label creation and only for DOM labels (not native canvas ones).
        onCreateLabel: function(domElement, node){
          domElement.innerHTML = node.name;
          var style = domElement.style;
          style.fontSize = "0.8em";
          style.color = "#ddd";
        },
        // Change node styles when DOM labels are placed
        // or moved.
        onPlaceLabel: function(domElement, node){
          var style = domElement.style;
          var left = parseInt(style.left);
          var top = parseInt(style.top);
          var w = domElement.offsetWidth;
          style.left = (left - w / 2) + 'px';
          style.top = (top + 10) + 'px';
          style.display = '';
        }
      });
      // load JSON data.

      fd.loadJSON(json);
      // compute positions incrementally and animate.
      fd.computeIncremental({
        iter: 40,
        property: 'end',
        onStep: function(perc){
          Log.write(perc + '% loaded...');
        },
        onComplete: function(){
          //Log.write('done');
          fd.animate({
            modes: ['linear'],
            transition: $jit.Trans.Elastic.easeOut,
            duration: 2500
          });
        }
      });
      // end


    /*
    //A client-side tree generator
    var getTree = (function() {
        var i = 0;
        return function(nodeId, level) {
          var subtree = eval('(' + json.replace(/id:\"([a-zA-Z0-9]+)\"/g,
          //var subtree = eval(json.replace(/id:\"([a-zA-Z0-9]+)\"/g,
          function(all, match) {
            return "id:\"" + match + "_" + i + "\""
          }) + ')');
          //}));
          $jit.json.prune(subtree, level); i++;
          return {
              'id': nodeId,
              'children': subtree.children
          };
        };
    })();


    //Implement a node rendering function called 'nodeline' that plots a straight line
    //when contracting or expanding a subtree.
    $jit.ST.Plot.NodeTypes.implement({
        'nodeline': {
          'render': function(node, canvas, animating) {
                if(animating === 'expand' || animating === 'contract') {
                  var pos = node.pos.getc(true), nconfig = this.node, data = node.data;
                  var width  = nconfig.width, height = nconfig.height;
                  var algnPos = this.getAlignedPos(pos, width, height);
                  var ctx = canvas.getCtx(), ort = this.config.orientation;
                  ctx.beginPath();
                  if(ort == 'left' || ort == 'right') {
                      ctx.moveTo(algnPos.x, algnPos.y + height / 2);
                      ctx.lineTo(algnPos.x + width, algnPos.y + height / 2);
                  } else {
                      ctx.moveTo(algnPos.x + width / 2, algnPos.y);
                      ctx.lineTo(algnPos.x + width / 2, algnPos.y + height);
                  }
                  ctx.stroke();
              }
          }
        }

    });

    //init Spacetree
    //Create a new ST instance
    var st = new $jit.ST({
        'injectInto': 'infovis',
        //set duration for the animation
        duration: 800,
        //set animation transition type
        transition: $jit.Trans.Quart.easeInOut,
        //set distance between node and its children
        levelDistance: 40,
        //set max levels to show. Useful when used with
        //the request method for requesting trees of specific depth
        levelsToShow: 1,//2,
        //set node and edge styles
        //set overridable=true for styling individual
        //nodes or edges
        Node: {
            height: 20,
            width: 40,
            //use a custom
            //node rendering function
            type: 'nodeline',
            color:'#23A4FF',
            lineWidth: 2,
            align:"center",
            overridable: true
        },

        Edge: {
            type: 'bezier',
            lineWidth: 2,
            color:'#23A4FF',
            overridable: true
        },

        //Add a request method for requesting on-demand json trees.
        //This method gets called when a node
        //is clicked and its subtree has a smaller depth
        //than the one specified by the levelsToShow parameter.
        //In that case a subtree is requested and is added to the dataset.
        //This method is asynchronous, so you can make an Ajax request for that
        //subtree and then handle it to the onComplete callback.
        //Here we just use a client-side tree generator (the getTree function).
        request: function(nodeId, level, onComplete) {
          var ans = getTree(nodeId, level);
          onComplete.onComplete(nodeId, ans);
        },

        onBeforeCompute: function(node){
            Log.write("loading " + node.name);
        },

        onAfterCompute: function(){
            Log.write("done");
        },

        //This method is called on DOM label creation.
        //Use this method to add event handlers and styles to
        //your node.
        onCreateLabel: function(label, node){
            label.id = node.id;
            label.innerHTML = node.name;
            label.onclick = function(){
                st.onClick(node.id);
            };
            //set label styles
            var style = label.style;
            style.width = 40 + 'px';
            style.height = 17 + 'px';
            style.cursor = 'pointer';
            style.color = '#fff';
            //style.backgroundColor = '#1a1a1a';
            style.fontSize = '0.8em';
            style.textAlign= 'center';
            style.textDecoration = 'underline';
            style.paddingTop = '3px';
        },

        //This method is called right before plotting
        //a node. It's useful for changing an individual node
        //style properties before plotting it.
        //The data properties prefixed with a dollar
        //sign will override the global node style properties.
        onBeforePlotNode: function(node){
            //add some color to the nodes in the path between the
            //root node and the selected node.
            if (node.selected) {
                node.data.$color = "#ff7";
            }
            else {
                delete node.data.$color;
            }
        },

        //This method is called right before plotting
        //an edge. It's useful for changing an individual edge
        //style properties before plotting it.
        //Edge data proprties prefixed with a dollar sign will
        //override the Edge global style properties.
        onBeforePlotLine: function(adj){
            if (adj.nodeFrom.selected && adj.nodeTo.selected) {
                adj.data.$color = "#eed";
                adj.data.$lineWidth = 3;
            }
            else {
                delete adj.data.$color;
                delete adj.data.$lineWidth;
            }
        }
    });
    //load json data
    st.loadJSON(eval( '(' + json + ')' ));
    //st.loadJSON(json);
    //compute node positions and layout
    st.compute();
    //emulate a click on the root node.
    st.onClick(st.root);
    //end
    //Add event handlers to switch spacetree orientation.
    */
    //end

    }
    </script>


  </body>
</html>


